import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

import vuexPersist from "vuex-persist";
//vuex配套的持久化插件
// 1.安装 cnpm i vuex-persist --save
// 2.引入 import vuexPersist from "vuex-persist";
// 3.配置
// plugins: [
//     new vuexPersist({
//         storage: window.localStorage,
//     }).plugin,
// ],
//配置vuex本地存储插件

export default new Vuex.Store({
    state: {
        shoplist: [],
    },
    mutations: {
        add(state, i) {
            var flag = false;
            state.shoplist.forEach((item) => {
                if (item.cid == i.cid) {
                    flag = true;
                    item.num++;
                }
            });
            if (flag == false) {
                 Vue.set(i, "num", 1);
                Vue.set(i, "card", 1);
                state.shoplist.push(i);
            }
        },
        plus(state, id) {
            state.shoplist.forEach((item) => {
                if (item.cid == id) {
                    item.num++;
                }
            });
        },
        min(state, id) {
            state.shoplist.forEach((item) => {
                if (item.cid == id) {
                    item.num--;
                }
            });
        },
        clear(state) {
            state.shoplist = [];
        },
          changecard(state, i) {
            // state.shoplist[index].num--;
            // state.shoplist[index].card = 2;
            state.shoplist.forEach((item) => {
                if (i.cid == item.cid) {
                    item.num--;
                    let mid = JSON.parse(JSON.stringify(item));
                    let obj = Object.assign(mid, { num: 1, card: 2 });
                    // console.log(state.shoplist);

                    state.shoplist.push(obj);
                }
            });
        },
        //放入二号口袋
    },
    getters: {
        sum(state) {
            let res = 0;
            state.shoplist.forEach((item) => {
                res += item.price * item.num;
            });
            return res;
        },
        //计算总价
    },

    actions: {},
    modules: {},
    plugins: [
        new vuexPersist({
            storage: window.localStorage,
        }).plugin,
    ],
    //配置vuex本地存储插件
});
